<template>
  <div class="trend-chart-container">
    <!-- 标题栏 -->
    <div class="header">
      <h3 class="title">实时趋势</h3>
      <div class="time-stamp">{{ currentTime }}</div>
      <div
        class="status-indicator"
        :class="{
          'status-normal': systemStatus,
          'status-error': !systemStatus,
        }"
      ></div>
    </div>

    <!-- 图表区域 - 使用echarts -->
    <div class="chart-area" ref="chartContainer"></div>

    <!-- 按钮区域 -->
    <div class="button-area">
      <button class="variable-select-btn" @click="showVariableList = true">
        变量选择
      </button>
      <button class="history-trend-btn">历史趋势</button>
    </div>

    <!-- 变量选择窗口 -->
    <div
      v-if="showVariableList"
      class="variable-list-overlay"
      @click="closeVariableList"
    >
      <div class="variable-list-container" @click.stop>
        <div class="variable-list-header">
          <h3>选择变量</h3>
          <button class="close-btn" @click="closeVariableList">×</button>
        </div>
        <div class="variable-list-content">
          <div
            v-for="variable in availableVariables"
            :key="variable.key"
            class="variable-item"
          >
            <label class="checkbox-label">
              <input
                type="checkbox"
                :value="variable.key"
                v-model="selectedVariableKeys"
              />
              <span class="variable-name">{{ variable.name }}</span>
              <span class="variable-unit">{{ variable.unit }}</span>
            </label>
          </div>
        </div>
        <div class="variable-list-footer">
          <button class="confirm-btn" @click="confirmVariableSelection">
            确定
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {
  ref,
  onMounted,
  onUnmounted,
  watch,
  nextTick,
  onBeforeUnmount,
} from "vue";
import * as echarts from "echarts";
import StartModelWsService from "@/ws_service/startModelWsService";

// 响应式数据
const currentTime = ref("");
const systemStatus = ref(true);
const showVariableList = ref(false);
const selectedVariableKeys = ref([]);
const selectedVariables = ref([]);
const chartContainer = ref(null);
const dataSeries = ref({}); // 存储每个变量的数据序列
const timeData = ref([]); // 存储时间数据

// 图表实例
let chartInstance = null;

// 图表配置
const MAX_DATA_POINTS = 100; // 最大数据点数量
const MAX_TIME_POINTS = 100; // 最大时间点数量
const TOTAL_DATA_THRESHOLD = 1500; // 数据总量阈值

// 曲线颜色 - 使用echarts推荐的颜色序列
const curveColors = [
  "#5470c6",
  "#91cc75",
  "#fac858",
  "#ee6666",
  "#73c0de",
  "#3ba272",
  "#fc8452",
  "#9a60b4",
  "#ea7ccc",
];

// 可用变量列表（与GeneratorParameter组件的allParameters保持一致）
const availableVariables = ref([
  { key: "2_38_0_0", name: "第一路风冷流量", unit: "m³/h" },
  { key: "2_39_0_0", name: "第二路风冷流量", unit: "m³/h" },
  { key: "2_40_0_0", name: "第三路风冷流量", unit: "m³/h" },
  { key: "2_36_0_0", name: "第四路风冷流量", unit: "m³/h" },
  { key: "1_3_0_0", name: "电压", unit: "V" },
  { key: "2_41_0_0", name: "水流量", unit: "L/min" },
  { key: "1_2_0_0", name: "电流", unit: "A" },
  { key: "power", name: "功率", unit: "W" }, // 计算型参数：电压*电流
  { key: "1_17_0_0", name: "发电机定子绕组温度1", unit: "°C" },
  { key: "1_18_0_0", name: "发电机定子绕组温度2", unit: "°C" },
  { key: "1_19_0_0", name: "发电机定子绕组温度3", unit: "°C" },
  { key: "1_20_0_0", name: "发电机定子绕组温度4", unit: "°C" },
]);

// 更新时间
const updateTime = () => {
  // 获取过去的本地时间，例如过去1小时
  const now = new Date();
  currentTime.value = now.toLocaleString().slice(0, 19).replace("T", " ");
};

// 初始化图表
const initChart = () => {
  if (!chartContainer.value) return;

  chartInstance = echarts.init(chartContainer.value);

  const option = {
    backgroundColor: "#ffffff",
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross",
        label: {
          backgroundColor: "#6a7985",
        },
      },
    },
    legend: {
      data: [],
      top: 10,
      textStyle: {
        color: "#333",
      },
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "10%",
      top: "15%",
      containLabel: true,
    },
    xAxis: {
      type: "time",
      boundaryGap: false,
      data: [],
      axisLabel: {
        color: "#666",
        formatter: (value) => {
          const date = new Date(value);
          return `${date.getSeconds()}`;
        },
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: "#f0f0f0",
          type: "dashed",
        },
      },
    },
    yAxis: {
      type: "value",
      axisLabel: {
        color: "#666",
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: "#f0f0f0",
          type: "dashed",
        },
      },
    },
    series: [],
  };

  chartInstance.setOption(option);

  // 响应式调整
  window.addEventListener("resize", handleResize);
};

// 处理窗口大小变化
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
};

// 更新图表数据
const updateChart = () => {
  if (!chartInstance || selectedVariables.value.length === 0) return;

  // 检查是否选中了发电机定子绕组温度
  const hasTemperatureSelected = selectedVariables.value.some(
    (variable) =>
      variable.key === "1_17_0_0" ||
      variable.key === "1_18_0_0" ||
      variable.key === "1_19_0_0" ||
      variable.key === "1_20_0_0"
  );

  const series = selectedVariables.value.map((variable, index) => {
    const variableData = dataSeries.value[variable.key] || [];
    // 创建时间和数值的对应数组
    const seriesData = timeData.value
      .slice(-variableData.length)
      .map((time, i) => [
        new Date(time).getTime(),
        variableData[
          variableData.length -
            timeData.value.slice(-variableData.length).length +
            i
        ] || 0,
      ]);

    return {
      name: `${variable.name}(${variable.unit})`,
      type: "line",
      data: seriesData,
      smooth: true,
      symbol: "none",
      lineStyle: {
        color: curveColors[index % curveColors.length],
        width: 2,
      },
      emphasis: {
        focus: "series",
      },
      animation: false, // 实时数据不需要动画
    };
  });

  // 如果选中了发电机定子绕组温度，则添加165度的红色报警线

  if (hasTemperatureSelected && timeData.value.length > 0) {
    const latestTime = new Date(
      timeData.value[timeData.value.length - 1]
    ).getTime();
    const oldestTime = new Date(timeData.value[0]).getTime();

    series.push({
      name: "温度报警线(165°C)",
      type: "line",
      data: [
        [oldestTime, 165],
        [latestTime, 165],
      ],
      smooth: false,
      symbol: "none",
      lineStyle: {
          color: "#ff4444",
          width: 2,
          type: "dashed",
        },
      emphasis: {
        focus: "series",
      },
      animation: false,
      // 添加报警线提示文字
      markPoint: {
        symbolSize: 0,
        label: {
          formatter: '报警线',
          position: 'end',
          color: '#ff4444',
          fontSize: 14,
          fontWeight: 'bold',
          padding: [0, 0, 0, -10] // 调整文字位置，使其在Y轴左侧
        },
        data: [
          {
            name: '报警线',
            coord: [oldestTime, 165],
            value: '报警线'
          }
        ]
      }
    });
  }

  const legendData = selectedVariables.value.map(
    (variable) => `${variable.name}(${variable.unit})`
  );

  // 如果添加了温度报警线，也将其添加到图例中
  if (hasTemperatureSelected) {
    legendData.push("温度报警线(165°C)");
  }

  chartInstance.setOption({
    legend: {
      data: legendData,
    },
    series: series,
  });
};

// 计算当前数据总量
const calculateTotalDataPoints = () => {
  let total = 0;
  Object.values(dataSeries.value).forEach((series) => {
    total += series.length;
  });
  return total;
};

// 清理老旧数据
const cleanOldData = () => {
  const totalPoints = calculateTotalDataPoints();

  // 如果数据总量超过阈值，需要清理
  if (totalPoints >= TOTAL_DATA_THRESHOLD) {
    // 计算需要移除的数据量
    const pointsToRemove = totalPoints - TOTAL_DATA_THRESHOLD + 50; // 多移除一些作为缓冲

    // 为了高效清理，我们采用以下策略：
    // 1. 优先减少各个数据系列的长度
    // 2. 对所有数据系列进行等比例缩减
    const seriesKeys = Object.keys(dataSeries.value);
    const pointsPerSeries = Math.ceil(pointsToRemove / seriesKeys.length);

    // 清理每个数据系列
    seriesKeys.forEach((key) => {
      const series = dataSeries.value[key];
      if (series && series.length > MAX_DATA_POINTS / 2) {
        // 确保保留至少一半的最近数据
        const removeCount = Math.min(
          pointsPerSeries,
          series.length - MAX_DATA_POINTS / 2
        );
        dataSeries.value[key] = series.slice(removeCount);
      }
    });

    // 同步更新时间数据
    const maxSeriesLength = Math.max(
      ...Object.values(dataSeries.value).map((s) => s.length),
      0
    );
    if (timeData.value.length > maxSeriesLength) {
      timeData.value = timeData.value.slice(-maxSeriesLength);
    }
  }
};

// 处理WebSocket接收到的数据
const trendChartProcessData = (data) => {
  if (!data || typeof data !== "object") return;

  // 使用当前时间作为数据点时间戳
  const nowTime = new Date();
  const timeStr = nowTime.toLocaleString().slice(0, 19).replace("T", " ");

  // 添加时间点
  timeData.value.push(timeStr);
  if (timeData.value.length > MAX_TIME_POINTS) {
    timeData.value = timeData.value.slice(-MAX_TIME_POINTS);
  }

  // 更新数据序列
  Object.entries(data).forEach(([key, values]) => {
    if (Array.isArray(values) && values.length > 0) {
      const latestValue = values[values.length - 1];

      // 初始化该变量的数据序列（如果不存在）
      if (!dataSeries.value[key]) {
        dataSeries.value[key] = [];
      }

      // 添加新数据点
      dataSeries.value[key].push(latestValue.toFixed(3));

      // 限制单个数据系列的数据点数量
      if (dataSeries.value[key].length > MAX_DATA_POINTS) {
        dataSeries.value[key] = dataSeries.value[key].slice(-MAX_DATA_POINTS);
      }
    }
  });

  // 计算功率值（电压*电流）
  const voltageData = data["1_3_0_0"];
  const currentData = data["1_2_0_0"];
  if (
    voltageData &&
    currentData &&
    voltageData.length > 0 &&
    currentData.length > 0
  ) {
    const voltage = voltageData[voltageData.length - 1];
    const current = currentData[currentData.length - 1];
    const power = voltage * current; // 功率 = 电压 * 电流

    // 初始化功率数据序列（如果不存在）
    if (!dataSeries.value["power"]) {
      dataSeries.value["power"] = [];
    }

    // 添加功率数据点
    dataSeries.value["power"].push(power.toFixed(3));

    // 限制功率数据系列的数据点数量
    if (dataSeries.value["power"].length > MAX_DATA_POINTS) {
      dataSeries.value["power"] = dataSeries.value["power"].slice(
        -MAX_DATA_POINTS
      );
    }
  }

  // 检查并清理超出阈值的数据总量
  cleanOldData();

  // 更新图表
  nextTick(() => {
    updateChart();
  });
};

// 关闭变量选择列表
const closeVariableList = () => {
  showVariableList.value = false;
};

// 确认变量选择
const confirmVariableSelection = () => {
  // 更新选中的变量
  selectedVariables.value = availableVariables.value.filter((variable) =>
    selectedVariableKeys.value.includes(variable.key)
  );

  // 获取之前所有的变量键
  const previousKeys = Object.keys(dataSeries.value);
  
  // 获取当前选中的变量键
  const currentKeys = selectedVariableKeys.value;
  
  // 清除未选中变量的数据
  previousKeys.forEach(key => {
    if (!currentKeys.includes(key)) {
      delete dataSeries.value[key];
    }
  });

  // 为新选择的变量初始化数据
  selectedVariables.value.forEach((variable) => {
    if (!dataSeries.value[variable.key]) {
      dataSeries.value[variable.key] = [];
    }
  });

  // 更新图表
  updateChart();

  closeVariableList();
};

// 定时器引用
let timeTimer = null;

// 生命周期钩子
onMounted(() => {
  // 设置时间更新定时器
  updateTime();
  timeTimer = setInterval(updateTime, 1000);

  // 初始化图表
  nextTick(() => {
    initChart();
  });

  // 订阅WebSocket数据
  StartModelWsService.onProcessedData(trendChartProcessData);

  // 默认选择第一个变量
  if (availableVariables.value.length > 0) {
    selectedVariableKeys.value = [availableVariables.value[0].key];
    selectedVariables.value = [availableVariables.value[0]];
    // 初始化默认变量的数据序列
    dataSeries.value[availableVariables.value[0].key] = [];
  }
});

onUnmounted(() => {
  StartModelWsService.offProcessedData(trendChartProcessData);
});
// 组件卸载前清理
onBeforeUnmount(() => {
  // 清除定时器
  if (timeTimer) clearInterval(timeTimer);

  // 取消订阅
  StartModelWsService.offProcessedData(trendChartProcessData);

  // 销毁图表实例
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }

  // 移除事件监听器
  window.removeEventListener("resize", handleResize);
});

// 监听选择的变量变化
watch(selectedVariables, () => {
  updateChart();
});
</script>

<style scoped>
.trend-chart-container {
  background-color: #2c3e50;
  border-radius: 8px;
  padding: 16px;
  color: #ecf0f1;
  font-family: Arial, sans-serif;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
  max-width: 100%;
  overflow: hidden;
  position: relative;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 2px solid #34495e;
}

.title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #3498db;
}

.time-stamp {
  font-size: 14px;
  color: #95a5a6;
}

.status-indicator {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  margin-left: 12px;
}

.status-normal {
  background-color: #27ae60;
  box-shadow: 0 0 8px rgba(39, 174, 96, 0.6);
}

.status-error {
  background-color: #e74c3c;
  box-shadow: 0 0 8px rgba(231, 76, 60, 0.6);
}

.chart-area {
  width: 100%;
  height: 400px;
  background-color: #ffffff;
  position: relative;
  margin-bottom: 16px;
  border: 1px solid #ddd;
  overflow: hidden;
}

.grid-lines {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
}

.grid-line {
  position: absolute;
  background-color: #f0f0f0;
}

.grid-line.horizontal {
  height: 1px;
  left: 0;
  right: 0;
}

.grid-line.vertical {
  width: 1px;
  top: 0;
  bottom: 0;
}

.grid-label {
  position: absolute;
  font-size: 12px;
  color: #666;
  background-color: #fff;
  padding: 0 4px;
}

.grid-label.left {
  left: 4px;
  top: 50%;
  transform: translateY(-50%);
}

.grid-label.bottom {
  bottom: 4px;
  left: 50%;
  transform: translateX(-50%);
}

.curves-container {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.curve-svg {
  width: 100%;
  height: 100%;
}

.button-area {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.variable-select-btn,
.history-trend-btn {
  padding: 8px 16px;
  background-color: #3498db;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.variable-select-btn:hover,
.history-trend-btn:hover {
  background-color: #2980b9;
}

/* 变量选择窗口 */
.variable-list-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.variable-list-container {
  background-color: #2c3e50;
  border-radius: 8px;
  width: 500px;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
}

.variable-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #34495e;
}

.variable-list-header h3 {
  margin: 0;
  color: #3498db;
}

.close-btn {
  background: none;
  border: none;
  color: #ecf0f1;
  font-size: 24px;
  cursor: pointer;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.close-btn:hover {
  background-color: #34495e;
}

.variable-list-content {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

.variable-item {
  margin-bottom: 8px;
}

.checkbox-label {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.checkbox-label:hover {
  background-color: #34495e;
}

.checkbox-label input[type="checkbox"] {
  width: 16px;
  height: 16px;
  cursor: pointer;
}

.variable-name {
  flex: 1;
  color: #ecf0f1;
}

.variable-unit {
  color: #95a5a6;
  font-size: 12px;
}

.variable-list-footer {
  padding: 16px;
  border-top: 1px solid #34495e;
  display: flex;
  justify-content: flex-end;
}

.confirm-btn {
  padding: 8px 24px;
  background-color: #27ae60;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.confirm-btn:hover {
  background-color: #229954;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chart-area {
    height: 300px;
  }

  .variable-list-container {
    width: 90vw;
    max-width: 500px;
  }

  .header {
    flex-wrap: wrap;
    gap: 10px;
  }

  .title {
    width: 100%;
    text-align: center;
  }

  .button-area {
    justify-content: center;
  }
}
</style>